Skip to content

Conversation

@stepan662
Copy link
Contributor

@stepan662 stepan662 commented May 20, 2025

Summary by CodeRabbit

  • New Features

    • Added support for extracting translation keys from global tolgee.t function calls across React, Vue, Svelte, and Angular projects.
  • Bug Fixes

    • Fixed naming inconsistencies in merger functions used by the parser.
  • Tests

    • Introduced new test cases to verify extraction from global tolgee.t function calls in React, Vue, Svelte, and Angular.
    • Updated Vue tests to ensure only appropriate translation calls are extracted.
  • Refactor

    • Improved and unified rule and merger handling for translation function detection across supported frameworks.

@coderabbitai
Copy link

coderabbitai bot commented May 20, 2025

Walkthrough

This update introduces support for extracting translation keys from calls to a global tolgee.t function across React, Vue, Svelte, and Angular (Ngx) parsers. It adds a new parser rule and token type, refactors merger naming for consistency, and replaces the Vue $t merger with a more general custom translation call merger. New unit tests verify correct extraction behavior for the new function call pattern.

Changes

File(s) Change Summary
src/extractor/parser/generalMapper.ts Extended GeneralTokenType union to include 'trigger.global.t.function'.
src/extractor/parser/parser.ts Renamed DEFAULT_MERGERERS to DEFAULT_MERGERS; fixed merger import names; added customTCallMerger to mergers.
src/extractor/parser/rules/globalTFunction.ts Added new exported rule globalTFunction for handling global T function calls.
src/extractor/parser/tokenMergers/customTCallMerger.ts Introduced customTCallMerger function for custom translation call token merging.
src/extractor/parser/tokenMergers/typesAsMerger.ts, src/extractor/parser/tokenMergers/typesCastMerger.ts Renamed exports: typesAsMergerertypesAsMerger, typesCastMergerertypesCastMerger.
src/extractor/parserNgx/ParserNgx.ts, src/extractor/parserReact/ParserReact.ts, src/extractor/parserSvelte/ParserSvelte.ts Updated to use DEFAULT_MERGERS, added globalTFunction as first rule in each parser.
src/extractor/parserVue/ParserVue.ts Updated to use DEFAULT_MERGERS, replaced globalTFunctionMerger with customTCallMerger for $t and this.$t.
src/extractor/parserVue/rules/globalTFunction.ts, src/extractor/parserVue/tokenMergers/globalTFunctionMerger.ts Deleted Vue-specific global T function rule and merger, replaced by generic implementations.
test/unit/extractor/ngx/translateService.test.ts, test/unit/extractor/react/useTranslate.test.ts, test/unit/extractor/svelte/getTranslate.test.ts, test/unit/extractor/vue/globalT.test.ts Added new test suites and cases to verify extraction of translation keys from global tolgee.t calls and refined Vue $t extraction tests.

Sequence Diagram(s)

sequenceDiagram
    participant SourceCode
    participant Parser
    participant TokenMerger
    participant Rule_globalTFunction
    participant ExtractedKeys

    SourceCode->>Parser: Parse source for translation calls
    Parser->>TokenMerger: Apply mergers (including customTCallMerger)
    TokenMerger-->>Parser: Return merged tokens
    Parser->>Rule_globalTFunction: Trigger on 'tolgee.t' call
    Rule_globalTFunction-->>Parser: Parse and extract key
    Parser->>ExtractedKeys: Add extracted key
Loading

Poem

A rabbit hops through code anew,
Sniffing out each tolgee.t clue.
From React, Vue, Svelte, and Ngx land,
Translation keys are close at hand!
With mergers neat and rules in line,
Extraction now works just fine.
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm warn config production Use --omit=dev instead.
npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-05-20T14_35_02_849Z-debug-0.log

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
src/extractor/parserVue/ParserVue.ts (1)

52-59: 💡 Verification agent

🧩 Analysis chain

Verify that globalTFunction rule is properly integrated

The integration of globalTFunction as the first rule in the rules array seems correct. This enables the parser to extract translation keys from global tolgee.t function calls.


🏁 Script executed:

#!/bin/bash
# Verify that tolgee.t function calls are properly detected
# Let's check the test files to ensure there are tests for this functionality

echo "Checking for Vue tolgee.t tests:"
fd ".*vue.*test.*" --type f | xargs grep -l "tolgee.t" | head -n 3

Length of output: 141


Add test coverage for globalTFunction in Vue parser

I didn’t find any existing tests verifying that the globalTFunction rule correctly extracts tolgee.t(…) calls in Vue single-file components. Please add or update your test suite to cover this new rule. For example:

  • Create a test (e.g. ParserVue.spec.ts or ParserVue.test.ts) alongside src/extractor/parserVue/ParserVue.ts.
  • Include a Vue SFC fixture using tolgee.t('my.key') in both <template> and <script>.
  • Assert that running the parser yields the expected translation key.
🧹 Nitpick comments (2)
src/extractor/parser/rules/globalTFunction.ts (1)

5-10: New rule implementation for parsing global tolgee.t function calls

The implementation correctly defines a rule with the appropriate trigger and delegates to the general tFunction parser with context dependency set to false.

Consider reviewing the as any type assertion at the end of the declaration. While it might be necessary for compatibility reasons, type assertions to any can sometimes hide potential type issues.

-} satisfies RuleType<GeneralTokenType> as any;
+} satisfies RuleType<GeneralTokenType>;

If removing the assertion causes type errors, it might be worth documenting why it's needed.

src/extractor/parser/tokenMergers/customTCallMerger.ts (1)

12-14: Consider additional pattern matching flexibility

The current implementation only matches expressions that start exactly with the accumulated state plus token. Consider adding more flexibility to handle variations like whitespace or alternative syntactic forms.

-        if (customExpressions.find((e) => e.startsWith(state + token))) {
+        const nextState = state + token;
+        if (customExpressions.find((e) => e.startsWith(nextState) || 
+            // Optional: More flexible matching logic here
+            e.replace(/\s+/g, '') === nextState.replace(/\s+/g, '')
+        )) {
           return state + token;
         }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between e75c268 and ecfc153.

📒 Files selected for processing (16)
  • src/extractor/parser/generalMapper.ts (1 hunks)
  • src/extractor/parser/parser.ts (2 hunks)
  • src/extractor/parser/rules/globalTFunction.ts (1 hunks)
  • src/extractor/parser/tokenMergers/customTCallMerger.ts (1 hunks)
  • src/extractor/parser/tokenMergers/typesAsMerger.ts (1 hunks)
  • src/extractor/parser/tokenMergers/typesCastMerger.ts (1 hunks)
  • src/extractor/parserNgx/ParserNgx.ts (4 hunks)
  • src/extractor/parserReact/ParserReact.ts (4 hunks)
  • src/extractor/parserSvelte/ParserSvelte.ts (4 hunks)
  • src/extractor/parserVue/ParserVue.ts (2 hunks)
  • src/extractor/parserVue/rules/globalTFunction.ts (0 hunks)
  • src/extractor/parserVue/tokenMergers/globalTFunctionMerger.ts (0 hunks)
  • test/unit/extractor/ngx/translateService.test.ts (1 hunks)
  • test/unit/extractor/react/useTranslate.test.ts (1 hunks)
  • test/unit/extractor/svelte/getTranslate.test.ts (1 hunks)
  • test/unit/extractor/vue/globalT.test.ts (2 hunks)
💤 Files with no reviewable changes (2)
  • src/extractor/parserVue/rules/globalTFunction.ts
  • src/extractor/parserVue/tokenMergers/globalTFunctionMerger.ts
🧰 Additional context used
🧬 Code Graph Analysis (6)
src/extractor/parserNgx/ParserNgx.ts (5)
src/extractor/parser/parser.ts (1)
  • DEFAULT_MERGERS (39-46)
src/extractor/parser/rules/globalTFunction.ts (1)
  • globalTFunction (5-10)
src/extractor/parserNgx/rules/componentWithT.ts (1)
  • componentWithT (13-52)
src/extractor/parserNgx/rules/translatePipe.ts (1)
  • translatePipe (8-58)
src/extractor/parserNgx/rules/translateFunction.ts (1)
  • translateFunction (5-10)
src/extractor/parser/rules/globalTFunction.ts (3)
src/extractor/parser/rules/tFunctionGeneral.ts (1)
  • tFunctionGeneral (7-52)
src/extractor/parser/types.ts (1)
  • RuleType (65-68)
src/extractor/parser/generalMapper.ts (1)
  • GeneralTokenType (102-117)
src/extractor/parserReact/ParserReact.ts (2)
src/extractor/parser/parser.ts (1)
  • DEFAULT_MERGERS (39-46)
src/extractor/parser/rules/globalTFunction.ts (1)
  • globalTFunction (5-10)
src/extractor/parserVue/ParserVue.ts (3)
src/extractor/parser/parser.ts (1)
  • DEFAULT_MERGERS (39-46)
src/extractor/parserVue/tokenMergers/hyphenPropsMerger.ts (1)
  • hyphenPropsMerger (11-30)
src/extractor/parser/tokenMergers/customTCallMerger.ts (1)
  • customTCallMerger (4-25)
src/extractor/parser/tokenMergers/customTCallMerger.ts (2)
src/extractor/parser/mergerMachine.ts (1)
  • MachineType (9-23)
src/extractor/parserReact/ParserReact.ts (1)
  • ReactMappedTokenType (21-23)
src/extractor/parserSvelte/ParserSvelte.ts (3)
src/extractor/parser/parser.ts (1)
  • DEFAULT_MERGERS (39-46)
src/extractor/parser/rules/globalTFunction.ts (1)
  • globalTFunction (5-10)
src/extractor/parserSvelte/rules/useTranslate.ts (1)
  • getTranslate (5-10)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: E2E Tests (ubuntu-latest, 22)
  • GitHub Check: E2E Tests (ubuntu-latest, 20)
  • GitHub Check: E2E Tests (ubuntu-latest, 18)
🔇 Additional comments (28)
src/extractor/parser/tokenMergers/typesAsMerger.ts (1)

7-7: Renamed merger for improved consistency

The export name was corrected from typesAsMergerer to typesAsMerger, removing the redundant "er" suffix and aligning with the consistent naming conventions used across parser token mergers.

src/extractor/parser/tokenMergers/typesCastMerger.ts (1)

7-7: Renamed merger for improved consistency

The export name was corrected from typesCastMergerer to typesCastMerger, removing the redundant "er" suffix for consistent naming with other merger components.

src/extractor/parser/generalMapper.ts (1)

116-117: Added new token type for global tolgee.t function support

Added a new token type 'trigger.global.t.function' to the GeneralTokenType type alias, which enables the parser to recognize and extract keys from global tolgee.t function calls.

test/unit/extractor/react/useTranslate.test.ts (1)

540-551: Added test coverage for global tolgee.t function extraction

New test suite added to verify the extractor can correctly identify and extract translation keys from global tolgee.t function calls in React components.

The test ensures that the key extraction works properly with the new global function support, which is consistent with similar tests added for Vue, Svelte, and Angular frameworks.

src/extractor/parser/parser.ts (2)

24-26: Good naming consistency fix and addition of customTCallMerger

The renaming from typesAsMergerer and typesCastMergerer to typesAsMerger and typesCastMerger improves naming consistency. Adding the customTCallMerger import properly sets up support for global tolgee.t function calls.


39-46: Well-structured changes to DEFAULT_MERGERS

The renaming from DEFAULT_MERGERERS to DEFAULT_MERGERS matches the improved naming convention, and including customTCallMerger(['tolgee.t']) adds the necessary support for extracting translation keys from global tolgee.t function calls.

src/extractor/parserReact/ParserReact.ts (4)

2-2: Fixed import for DEFAULT_MERGERS

Correctly updated the import to use the renamed constant.


17-17: Good addition of globalTFunction import

Properly imports the new parsing rule needed for global translation function support.


26-26: Fixed reference to DEFAULT_MERGERS

Using the renamed constant correctly.


45-51: Well-structured addition of globalTFunction rule

The rules array is properly updated to include the new globalTFunction rule, positioned as the first rule to be evaluated. This ensures proper extraction of translation keys from global tolgee.t function calls in React components.

test/unit/extractor/vue/globalT.test.ts (2)

73-81: Improved test case clarity

The test description now more accurately reflects what's being tested: that only specific $t usage patterns are extracted. Adding the foo.$t('key3') call helps verify that translation calls on other objects are correctly ignored.


278-291: Good test coverage for global tolgee.t function

This new test case effectively verifies that the extractor correctly identifies and extracts translation keys from global tolgee.t function calls in Vue components. The test is simple but comprehensive, checking both key extraction and confirming no warnings are generated.

test/unit/extractor/svelte/getTranslate.test.ts (1)

398-411: Good test coverage for global tolgee.t function in Svelte

This test case mirrors the Vue test, ensuring consistent behavior across frameworks. It verifies that the extractor correctly identifies and extracts translation keys from global tolgee.t function calls in Svelte components.

test/unit/extractor/ngx/translateService.test.ts (1)

161-172: Test looks good for basic global tolgee.t function support

The test verifies that the extraction correctly identifies translation keys from global tolgee.t function calls. The implementation is straightforward and tests both the extraction of the key and the absence of warnings.

src/extractor/parserNgx/ParserNgx.ts (4)

2-2: Fixed typo in import statement

Corrected the import from DEFAULT_MERGERERS to DEFAULT_MERGERS.


16-16: Added import for globalTFunction rule

This import is necessary to support the new functionality for extracting keys from global tolgee.t function calls.


25-25: Fixed typo in array spread operator usage

Updated to spread DEFAULT_MERGERS instead of the previously misspelled DEFAULT_MERGERERS.


43-43: Added globalTFunction rule to parser rules

The rule is added as the first element in the array to ensure it takes precedence over other rules when applicable.

src/extractor/parserSvelte/ParserSvelte.ts (4)

2-2: Fixed typo in import statement

Corrected the import from DEFAULT_MERGERERS to DEFAULT_MERGERS.


18-18: Added import for globalTFunction rule

This import is needed to support extraction of translation keys from global tolgee.t function calls in Svelte components.


27-27: Fixed typo in array spread operator usage

Updated to spread DEFAULT_MERGERS instead of the previously misspelled DEFAULT_MERGERERS.


46-46: Added globalTFunction rule to parser rules

The rule is added as the first element in the array, consistent with how it was added in the other parsers. This ensures consistent behavior across frameworks.

src/extractor/parserVue/ParserVue.ts (4)

2-2: Fixed import name for consistency

The import statement correctly uses DEFAULT_MERGERS instead of what was likely DEFAULT_MERGERERS, ensuring consistency with the actual exported constant name from the parser module.


14-14: Good refactoring: Using shared globalTFunction rule

Changed from a local path to using the shared implementation from ../parser/rules/globalTFunction.js. This promotes code reuse and consistency across different parsers.


21-21: Improved architecture: Replaced Vue-specific merger with generic customTCallMerger

The addition of customTCallMerger and its configuration with Vue-specific translation function names (['$t', 'this.$t']) replaces what was likely a Vue-specific implementation. This change creates a more unified approach to handling translation function calls across different framework parsers.

Also applies to: 32-32


30-30: Fixed naming consistency

Updated to use the correctly-named DEFAULT_MERGERS constant.

src/extractor/parser/tokenMergers/customTCallMerger.ts (2)

4-25: Well-implemented generic token merger for translation function calls

The customTCallMerger is a well-designed factory function that creates a token merger for custom translation function calls. It follows a state machine pattern to track and match token sequences, making it flexible for use across different parsers.

The implementation:

  1. Takes an array of custom expressions to match
  2. Processes tokens based on their type ('variable', 'function.call', 'acessor.dot', 'expression.begin')
  3. Builds up state as it encounters tokens that match the provided expressions
  4. Triggers a merge when it encounters a complete match
  5. Marks merged tokens with the custom type 'trigger.global.t.function'

This design allows the same core logic to be reused across different parsers with different translation function naming patterns.


23-24: Good type safety with satisfies operator

The use of as const satisfies MachineType<ReactMappedTokenType, string> ensures type safety while maintaining a specific return type. This is a modern TypeScript best practice.

@stepan662 stepan662 linked an issue May 20, 2025 that may be closed by this pull request
@stepan662 stepan662 merged commit 9a455d1 into main May 28, 2025
15 checks passed
@stepan662 stepan662 deleted the stepangranat/global-tolgee-t-function branch May 28, 2025 17:55
@github-actions
Copy link

🎉 This PR is included in version 2.11.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tolgee CLI should detect also tolgee.t in all integrations

3 participants